package com.web.exiaodao.remote.controller;

import com.web.exiaodao.business.entity.FanliBusiness;
import com.web.exiaodao.business.repository.FanliOrderRepository;
import com.web.exiaodao.business.service.FanliBusinessService;
import com.web.exiaodao.remote.service.ApiFanliOrderService;
import com.web.exiaodao.remote.vo.FanliOrderVo;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.controller.BaseController;
import com.web.webstart.base.util.XaUtil;
import com.web.webstart.base.util.jpa.WebUitl;
import com.web.webstart.base.util.result.XaResult;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author zhanglin
 * @version V1.0
 * @Title: ApiFanliOrderController.java
 * @Package com.web.exiaodao.remote.controller
 * @Description: 返利接口
 * @date 2017-02-13 14:46:51
 */
@Api(value = "fanli", description = "返利接口", position = 10)
@Controller
@RequestMapping("/api/fanli")
public class ApiFanliController extends BaseController {

    private static final Logger LOGGER = Logger.getLogger(ApiFanliController.class);

    @Autowired
    private ApiFanliOrderService fanliOrderService;

    @Autowired
    private FanliOrderRepository fanliOrderRepository;

    @Autowired
    private FanliBusinessService fanliBusinessService;

    /**
     * @return
     * @Title: findFanliBusiness
     * @Description: 查询所有返利商家
     */
    @ApiOperation(value = "查询所有返利商家", notes = "findFanliBusiness,当返回的code=1时，取出object进行显示,存放为数组对象")
    @ResponseBody
    @RequestMapping(value = "findFanliBusiness", method = RequestMethod.POST)
    public XaResult<Page<FanliBusiness>> findFanliOrderList(
    ) throws Exception {
        XaResult<Page<FanliBusiness>> xr = new XaResult<>();
        Pageable pageable = WebUitl.buildPageRequest(0, Integer.MAX_VALUE, "[{property:'createTime',direction:'DESC'}]");
        Map<String, Object> filterParams = WebUitl.getParametersStartingWith("{}", "search_");
        xr = fanliBusinessService.findListEQStatusByFilter(XaConstant.Status.valid, filterParams, pageable);
        return xr;
    }

    /**
     * @return
     * @Title: findFanliOrderList
     * @Description: 查询所有返利-订单表信息
     */
    @ApiOperation(value = "查询所有返利-订单表", notes = "查询所有返利-订单表信息,当返回的code=1时，取出object进行显示,存放为数组对象")
    @ResponseBody
    @RequestMapping(value = "findFanliOrderList", method = RequestMethod.POST)
    public XaResult<List<FanliOrderVo>> findFanliOrderList(
            @ApiParam("购买人ID,字段名:userId") @RequestParam(value = "userId") Long userId,
            @ApiParam("返利订单状态(0：即将可以（即将可以用返利）(最近下单) 1：已经返利 2：无返利 （已经返利要2个月),字段名:faliOrderStatus") @RequestParam(value = "faliOrderStatus", required = false) Integer faliOrderStatus,
            @ApiParam("页号,字段名:nextPage,默认0,从第0页开始") @RequestParam(defaultValue = "0", required = false) Integer nextPage,
            @ApiParam("页长,字段名:pageSize,默认10") @RequestParam(defaultValue = "10", required = false) Integer pageSize
    ) throws Exception {
        XaResult<List<FanliOrderVo>> xr = new XaResult<List<FanliOrderVo>>();
        Pageable pageable = WebUitl.buildPageRequest(nextPage, pageSize, "[{property:'createTime',direction:'DESC'}]");
        Map<String, Object> filterParams = WebUitl.getParametersStartingWith("{}", "search_");
        filterParams.put("EQ_userId", userId);
        if (XaUtil.isNotEmpty(faliOrderStatus)) {
            filterParams.put("EQ_faliOrderStatus", faliOrderStatus);
        }
        xr = fanliOrderService.findListEQStatusByFilter(XaConstant.Status.valid, filterParams, pageable);
        return xr;
    }


    /**
     * @return
     * @Title: findFanliOrderById
     * @Description: 根据ID查找单条实体
     * //@param modelId
     */
    @ApiOperation(value = "返利-订单表详情", notes = "查询返利-订单表详细信息,当返回的code=1时，取出object进行显示,存放为单体对象")
    @ResponseBody
    @RequestMapping(value = "findFanliOrderById", method = RequestMethod.POST)
    public XaResult<FanliOrderVo> findFanliOrderById(
            @ApiParam("编号,字段名:id,必填") @RequestParam(value = "id") Long id
    ) throws Exception {
        XaResult<FanliOrderVo> xr = new XaResult<FanliOrderVo>();
        xr = fanliOrderService.findOne(id);
        return xr;
    }


    /**
     * @return
     * @Title: fanli order
     * @Description: fanli order
     */
    @ApiOperation(value = "订单支付成功,合作方通知e孝", notes = "订单支付成功,合作方通知e孝道")
    @ResponseBody
    @RequestMapping(value = "notifyPaySucess", method = RequestMethod.POST)
    public void notifyPaySucess(
            HttpServletRequest request,
            HttpServletResponse reponse
    ) throws Exception {
        LOGGER.info("订单支付成功,合作方通知e孝 通知 开始");
        reponse.reset();
        PrintWriter out = reponse.getWriter();
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);
        }
        LOGGER.info(params);
        /**
         *
         key:跳转到商户携带的ukey
         orderNo:下单编号
         createOrderTime:下单时间
         orderMoney：订单金额
         shopName：商品名称
         shopBrief：商品简介
         shopImg：商品图片
         */
        FanliOrderVo.FanliTemporder temporder = new FanliOrderVo.FanliTemporder();
        temporder.setKey(params.get("key"));//ukey
        temporder.setOrderNo(params.get("orderNo"));
        temporder.setCreateOrderTime(params.get("createOrderTime"));
        temporder.setOrderMoney(params.get("orderMoney"));
        temporder.setShopName(params.get("shopName"));
        temporder.setShopBrief(params.get("shopBrief"));
        temporder.setShopImg(params.get("shopImg"));
        try {
            fanliOrderService.createFanliOrder(temporder);
            out.println("sucesss");
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error(e.getMessage(), e);
            out.println("fail");
        }
    }

    /**
     * 返利完成
     *
     * @return
     * @Title: notifyFanliResult  order
     */
    @ApiOperation(value = "返利完成，合作方通知e孝道", notes = "返利完成")
    @ResponseBody
    @RequestMapping(value = "notifyFanliResult ", method = RequestMethod.POST)
    public void notifyFanliResult(
            HttpServletRequest request,
            HttpServletResponse reponse
    ) throws Exception {
        LOGGER.info("订单支付成功,合作方通知e孝 通知 开始");
        reponse.reset();
        PrintWriter out = reponse.getWriter();
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);
        }
        LOGGER.info(params);
        /**
         e孝道请求参数：
         orderNo:订单编号
         客户返回参数：
         orderNo:订单编号
         fanliStatus: 1:可以正常返利 2:返利订单未完成 3:未找到返利订单
         failFanliInfo:说明返利完成和未完成的原因
         failExpectedFanliTime:返利未完成，预计返利日期yyyy-mm-dd
         */
        try {
            String orderNo = params.get("orderNo");
            String fanliStatus = params.get("fanliStatus");
            String failFanliInfo = params.get("failFanliInfo");
            String failExpectedFanliTime = params.get("failExpectedFanliTime");
            fanliOrderService.fanliOrderSucess(orderNo, fanliStatus, failFanliInfo, failExpectedFanliTime);
            out.println("sucesss");
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error(e.getMessage(), e);
            out.println("fail");
        }
    }
}

